import { NavBar, DatePicker } from 'antd-mobile'
import { useState, useEffect } from 'react'
import './index.scss'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
import { useMemo } from 'react'
import _groupBy from 'lodash/groupBy'
import DailyBill from './components/DayBill'

const Month = () => {
  const [dateVisible, setDateVisible] = useState(false)
  // 控制显示时间
  const [currentDate, setCurrentDate] = useState(() => {
    return dayjs(new Date()).format('YYYY-MM')
  })
  // 设置当前月份的数据
  const [currentMonthList, setCurrentMonthList] = useState([])
  // 获取账单数据
  const billList = useSelector((state) => state.bill.billList)

  //按月进行数据分组
  const monthGroup = useMemo(() => {
    return _groupBy(billList, (item) => {
      return dayjs(item.date).format('YYYY-MM')
    })
  }, [billList])

  // 当 monthGroup 更新时，设置当前月份的数据，
  useEffect(() => {
    const currentMonth = dayjs(new Date()).format('YYYY-MM')
    setCurrentMonthList(monthGroup[currentMonth] || [])
  }, [monthGroup])

  const onConfirm = (date) => {
    setDateVisible(false)
    const formatDate = dayjs(date).format('YYYY-MM')
    setCurrentMonthList(monthGroup[formatDate] || [])
    setCurrentDate(formatDate)
  }

  // 计算出这个月的总钱数
  const monthResult = useMemo(() => {
    const pay = currentMonthList
      .filter((item) => item.type === 'pay')
      .reduce((acc, item) => {
        return acc + Math.abs(item.money) // 支出取绝对值
      }, 0)
    const income = currentMonthList
      .filter((item) => item.type === 'income')
      .reduce((acc, item) => {
        return acc + item.money // 收入直接相加
      }, 0)
    return {
      pay,
      income,
      total: income - pay, // 结余 = 收入 - 支出
    }
  }, [currentMonthList])

  // 当前月按照日进行分组
  const dayGroup = useMemo(() => {
    const groupData = _groupBy(currentMonthList, (item) =>
      dayjs(item.date).format('YYYY-MM-DD')
    )
    const keys = Object.keys(groupData)
    return {
      groupData,
      keys,
    }
  }, [currentMonthList])
  console.log(dayGroup)

  return (
    <div className="monthlyBill">
      <NavBar className="nav" backArrow={false}>
        月度收支
      </NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setDateVisible(true)}>
            <span className="text">{currentDate + ''} 月账单</span>
            <span
              className={classNames('arrow', dateVisible && 'expand')}
            ></span>
          </div>
          {/* 统计区域 */}
          <div className="twoLineOverview">
            <div className="item">
              <span className="money">{monthResult.pay.toFixed(2)}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.income.toFixed(2)}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.total.toFixed(2)}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="month"
            visible={dateVisible}
            onCancel={() => setDateVisible(false)}
            onConfirm={onConfirm}
            onClose={() => setDateVisible(false)}
            max={new Date()}
          />
        </div>
        {dayGroup.keys.map((key) => {
          return (
            <DailyBill
              date={key}
              key={key}
              billList={dayGroup.groupData[key]}
            ></DailyBill>
          )
        })}
      </div>
    </div>
  )
}

export default Month
